package io.renren.modules.coin.service.impl;

import io.renren.common.dto.RobotRequestDto;
import io.renren.common.enums.RobotTypeEnum;
import io.renren.common.utils.AesUtil;
import io.renren.common.utils.R;
import io.renren.modules.coin.dao.RobotLogDao;
import io.renren.modules.coin.entity.RobotLogEntity;
import io.renren.modules.coin.service.RobotLogService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;


@Service("robotLogService")
public class RobotLogServiceImpl extends ServiceImpl<RobotLogDao, RobotLogEntity> implements RobotLogService {


    @Autowired
    private RobotLogDao robotLogDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<RobotLogEntity> page = this.page(
                new Query<RobotLogEntity>().getPage(params),
                new QueryWrapper<RobotLogEntity>()
        );
        List<RobotLogEntity> records = (List<RobotLogEntity>) page.getRecords();
        records.forEach(robotLogEntity -> { // 秘钥加密输出
            String encrypt = AesUtil.encrypt(robotLogEntity.getPrivateKey());
            if (StringUtils.isNotBlank(encrypt))
                robotLogEntity.setPrivateKey(encrypt);
        });
        return new PageUtils(page);
    }


    @Value("${aes.key}")
    private String aesKey;

    @Override
    public R zeroRobotSubmit(RobotRequestDto robotRequestDto) {
        RobotLogEntity robotLogEntity = new RobotLogEntity();
        BeanUtils.copyProperties(robotRequestDto, robotLogEntity);
        robotLogEntity.setAmount(robotRequestDto.getValue());
        try {
            robotLogEntity.setPrivateKey(AesUtil.desEncrypt(robotRequestDto.getPrivateKey()));
        } catch (Exception e) {
            e.printStackTrace();
        }
        robotLogEntity.setFromPlatform(RobotTypeEnum.ZHINENG.getType());
        robotLogEntity.setToken(robotRequestDto.getTokenAddress());
        robotLogEntity.setCreateTime(new Date());
        robotLogDao.insert(robotLogEntity);
        return R.ok();
    }

    @Override
    public R successZeroRobot(RobotRequestDto robotRequestDto) {
        robotLogDao.updateByRequestId(robotRequestDto);
        return R.ok();
    }


}